/*
 * 文件名：SubpackCotController.java
 * 版权：Copyright by www.infopub.top
 * 描述：
 * 修改人：wuzhiyang
 * 修改时间：2020年2月17日
 * 跟踪单号：
 * 修改单号：
 * 修改内容：
 */

package top.infopub.mgr.bpa.web;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.bpa.domain.SubpackCotDomain;
import top.infopub.mgr.bpa.domain.SubpackLedgerDomain;
import top.infopub.mgr.bpa.jsonVo.InnerAgrtJsonVo;
import top.infopub.mgr.bpa.jsonVo.SubpackCotJsonVo;
import top.infopub.mgr.bpa.service.*;
import top.infopub.mgr.bpa.vo.ContractManageVo;
import top.infopub.mgr.bpa.vo.SubpackCotVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.OrgInfoService;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.service.MarketManageService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.bpa.ContractExtDetail;
import top.infopub.model.bpa.InnerSupple;
import top.infopub.model.bpa.SubpackCot;
import top.infopub.model.hr.OrgInfo;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.ProjectAttachment;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**对内合同
 * @author wuzhiyang
 * @version 2020年2月17日
 * @see SubpackCotController
 * @since商务管理/对内合同/分包合同
 */
@Controller
@RequestMapping("/subpackCot")
public class SubpackCotController extends GenericFlowController {

    @Autowired
    private SubpackCotService subpackCotService;

    @Autowired
    private MarketManageService marketManageService;

    @Autowired
    private ContractExtDetailService contractExtDetailService;

    @Autowired
    private  InnerSuppleService innerSuppleService;

    @Autowired
    private ProProcessManageService proProcessManageService;
    @Autowired
    private BpaProcessManageService bpaProcessManageService;


    /**
     * 分包合同列表
     * @return
     * @see
     */
    @RequestMapping("/list")
    public String list(HttpServletRequest request) {
        //获取登录人员信息
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        //查询区域公司列表
        List<OrgInfo> orgInfoList = marketManageService.queryOrgInfoByAuthUserId(vo);
        request.setAttribute("orgInfoList", orgInfoList);
        //查询营销人员列表
        List<StaffInfo> staffInfoList = marketManageService.queryStaffInfoByAuthUserId(vo);
        request.setAttribute("staffInfoList", staffInfoList);
        return "bpa/lay-subpackCot-list";
    }

    /**
     * 分包合同评审列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<SubpackCotDomain> queryDataByCondition(SubpackCotVo subpackCotVo,
                                                        ParamPage paramPage) throws ParseException {
        Page<SubpackCotDomain> page = new Page<SubpackCotDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (subpackCotVo.getEndDate() != null) {
            subpackCotVo.setEndDate(DateUtils.addDays(subpackCotVo.getEndDate(), 1));
        }
        page = subpackCotService.selectByDomainWhere(page, subpackCotVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 分包合同台账
     *
     * @return
     */
    @RequestMapping("/selectByLedger")
    @ResponseBody
    public RspVo<SubpackLedgerDomain> selectByLedger(ContractManageVo contractManageVo, ParamPage paramPage) throws ParseException {
        Page<SubpackLedgerDomain> page = new Page<SubpackLedgerDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (contractManageVo.getEndDate() != null) {
            contractManageVo.setEndDate(top.infopub.mgr.util.DateUtils.addDays(contractManageVo.getEndDate(), 1));
        }
        page = subpackCotService.selectByLedger(page, contractManageVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     *@Description:  从内部协议合同评审获取项目下拉
     *@Param:
     *@return:
     *@Author: Tszzzzzzz
     *@date: 2021/6/17
     */
    @RequestMapping("/queryProject")
    @ResponseBody
    public RspVo queryProject(){
        return innerSuppleService.selectProject();
    }


    /**
    *@Description: 详情
    *@Param:
    *@return:
    *@Author: Tszzzzzzz
    *@date: 2021/6/23
    */
    @RequestMapping("/queryPackDetail")
    @ResponseBody
    public RspVo queryPackDetail (String id){
        return subpackCotService.queryPackDetail(id);
    }

    /**
    *@Description: 保存/修改
    *@Param:
    *@return:
    *@Author: Tszzzzzzz
    *@date: 2021/6/23
    */
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save (String bodyStr,Integer submitType){
        AuthorizationVO userDtl = SessionUserUtils.getSessionAttributeForUserDtl();
        String s = StringEscapeUtils.unescapeJava(bodyStr);
        SubpackCotJsonVo vo = JSON.parseObject(s,SubpackCotJsonVo.class);
        /**
         * 附件处理
         * */
        List<ProjectAttachment> attachmentList = new ArrayList<>();
        if(vo.getFileAtt()!=null){
            String[] fileAtt = vo.getFileAtt();
            for (String file : fileAtt) {
                ProjectAttachment attachment = createProjectFileAtta(userDtl,vo.getSubpackCot().getProCode(),file);
                attachmentList.add(attachment);
            }
        }
    return subpackCotService.saveAll(bodyStr,submitType,userDtl,vo.getSubpackCot(),vo.getInnerListings(),vo.getCotLists(),vo.getCompPlan(),attachmentList);
    }

    /**
     * 根据id查询设备合同详细  > 注意：方法命名必须为：toDealOrDetail
     *
     * @param id 分包合同id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("id",id);
        SubpackCot subpackCot = subpackCotService.selectBySguid(id);
        request.setAttribute("isAuditFlag", "1");
        if (subpackCot!=null){
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), subpackCot.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(subpackCot.getProcessId()) && subpackCot.getProcessId().length() > 10){
                request.setAttribute("processId", subpackCot.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(subpackCot.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), subpackCot.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        return new ModelAndView("bpa/lay-SubContractReview-detail");
    }

    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //审批
        bpaProcessManageService.auditProject(id, processId, status, auditMsg);
        return RspVo.getSuccessResponse();
    }
//    /**
//     * 分包合同-我审批的列表数据
//     *
//     * @return
//     */
//    @RequestMapping("/queryMyCheckDataByCondition")
//    @ResponseBody
//    public RspVo<SubpackCotDomain> queryMyCheckDataByCondition(SubpackCotVo subpackCotVo,
//                                                               ParamPage paramPage) {
//        Page<SubpackCotDomain> page = new Page<SubpackCotDomain>();
//        page.setPageNum(paramPage.getPage());
//        page.setPageSize(paramPage.getLimit());
//        //查询时，结束日期增加一天
//        if (subpackCotVo.getEndDate() != null) {
//            subpackCotVo.setEndDate(DateUtils.addDays(subpackCotVo.getEndDate(), 1));
//        }
//        subpackCotVo.setAddBy(SessionUserUtils.getSessionUserId());
//        page = subpackCotService.selectMyCheckByDomainWhere(page, subpackCotVo);
//        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
//    }

    /**
     * 分包合同-新增
     * @return
     */
//    @RequestMapping("/add")
//    public String toAdd(HttpServletRequest request) {
//        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
//        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
//        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
//        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
//        request.setAttribute("bindOrgId", bindOrgId);
//        request.setAttribute("bindOrgName", bindOrgName);
//        request.setAttribute("bindDeptId", bindDeptId);
//        request.setAttribute("bindDeptName", bindDeptName);
//        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
//        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
//        request.setAttribute("staffName", staffInfo.getStaffName());
//        //接收前端参数 判断 原合同  和  补充协议
//        String types = request.getParameter("types");
//        if ("1".equals(types)) {
//            //返回所有内部协议中的项目名称
//            List<InnerAgrt> InnerAgrtList = innerAgrtService.selectInnerAgrt();
//            request.setAttribute("InnerAgrtList", InnerAgrtList);
//            //返回所有合作单位为分包单位的信息
//            List<CoopInfo> coopInfoList = coopInfoService.selectAll(null, "4", null);
//            request.setAttribute("coopInfoList", coopInfoList);
//            return "bpa/lay-subpackCot-add-1";
//        }
//        else if ("2".equals(types)) {
//            //返回分包合同中的项目名称
//            List<SubpackCot> selectSubpackCotList = subpackCotService.selectSubpackCot();
//            request.setAttribute("subpackCotList", selectSubpackCotList);
//            return "bpa/lay-subpackCot-add-2";
//        }
//        return null;
//    }

//    /**
//     * 增加子项选择框(原合同和补充合同一样调用这个接口)
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping("/getselectByProCode")
//    @ResponseBody
//    public Map<String, Object> getselectByProCode(HttpServletRequest request) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        String proCodeAndCodes = request.getParameter("proCodeAndCodes");
//        String[] split = proCodeAndCodes.split("\\_");
//        try {
//            //增加子项选择框
//            ContractExt contractExt = contractExtService.selectByProCode(split[0]);
//            if (contractExt != null) {
//                List<ContractExtSub> subNamesList = contractExtSubService.selectAllBySubNames(contractExt.getId());
//                map.put("subNamesList", subNamesList);
//            }
//        }
//        catch (Exception e) {
//            log.error("查询子项记录异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }

    /**
     * 根据子项选择框带入费用明细表信息
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping("/getDetailBySubId")
    @ResponseBody
    public Map<String, Object> getDetailBySubId(HttpServletRequest request) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        String subId = request.getParameter("subId");
        try {
            //查询承继协议明细信息
            ContractExtDetail contractExtDetail = new ContractExtDetail();
            contractExtDetail.setExtSubId(subId);
            contractExtDetail.setFeeType(1);
            List<ContractExtDetail> contractExtDetails = contractExtDetailService.selectByEntityWhere(contractExtDetail);
            if (contractExtDetails != null && contractExtDetails.size() > 0) {
                map.put("contractExtDetails", contractExtDetails);
            }
        }
        catch (Exception e) {
            log.error("查询费用明细表记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 根据内部协议中项目编号查询相关带入信息(分包合同/原合同)
     * @param request
     * @return
     * @throws Exception
     */
//    @RequestMapping("/getInnerAgrtByProCode")
//    @ResponseBody
//    public Map<String, Object> getInnerAgrtByProCode(HttpServletRequest request) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        String proCodeAndCodes = request.getParameter("proCodeAndCodes");
//        String[] split = proCodeAndCodes.split("\\_");
//        try {
//            //带出内部协议的信息
//            Map<String, Object> mapWhere = new HashMap<String, Object>();
//            InnerAgrtDomain innerAgrtDomain = new InnerAgrtDomain();
//            mapWhere.put("refId", split[1]);
//            mapWhere.put("processStatus", "9");
//            mapWhere.put("orderCondition", "ADD_TIME desc");
//            List<InnerAgrt> innerAgrts = innerAgrtService.selectByMapWhere(mapWhere);
//            if (CollectionUtils.isNotEmpty(innerAgrts)) {
//                innerAgrtDomain = innerAgrtService.selectByIds(innerAgrts.get(0).getId());
//            }
//            else {
//                innerAgrtDomain = innerAgrtService.selectByIds(split[1]);
//            }
//            if (innerAgrtDomain != null) {
//                map.put("InnerAgrt", innerAgrtDomain);
//                //带出 合同清单子项  和  合同清单子项费用明细  信息
//                List<InnerAgrtDetailAndSubDomain> byInnerAgrtIdList = innerAgrtDetailService.selectByInnerAgrtId(innerAgrtDomain.getId());
//                List<InnerAgrtDetailAndSubDomain> list = new ArrayList<>();
//                for (InnerAgrtDetailAndSubDomain iSubDomain : byInnerAgrtIdList) {
//                    if (iSubDomain.getFeeSmallType() == -1) {
//                        iSubDomain.setPackPreFeeAmount(iSubDomain.getPackPreFee());
//                    }
//                    list.add(iSubDomain);
//                }
//                map.put("innerAgrtDetailAndSubList", list);
//            }
//            else {
//                flag = false;
//            }
//        }
//        catch (Exception e) {
//            log.error("查询内部协议记录异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }

//    /**
//     * 根据分包合同中项目编号查询相关带入信息(分包合同/补充合同)
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping("/getSubpackCotByProCode")
//    @ResponseBody
//    public Map<String, Object> getSubpackCotByProCode(HttpServletRequest request) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        String proCodeAndCodes = request.getParameter("proCodeAndCodes");
//        String[] split = proCodeAndCodes.split("\\_");
//        try {
//            Map<String, Object> mapWhere = new HashMap<String, Object>();
//            SubpackCotDomain subpackCotDomain = new SubpackCotDomain();
//            mapWhere.put("refId", split[1]);
//            mapWhere.put("processStatus", "9");
//            mapWhere.put("orderCondition", "ADD_TIME desc");
//            List<SubpackCot> subpackCots = subpackCotService.selectByMapWhere(mapWhere);
//            if (CollectionUtils.isNotEmpty(subpackCots)) {
//                subpackCotDomain = subpackCotService.selectById(subpackCots.get(0).getId());
//            }
//            else {
//                subpackCotDomain = subpackCotService.selectById(split[1]);
//            }
//            //带出分包合同中的信息
//            //SubpackCotDomain subpackCotDomain = subpackCotService.selectBySubpackCotVersionProCode(split[1]);
//            if (subpackCotDomain != null) {
//                map.put("subpackCotDomain", subpackCotDomain);
//                //带出 合同清单子项  和  合同清单子项费用明细  信息
//                List<SubpackCotDetailAndSubDomain> subpackCotIdList = subpackCotDetailService.selectBySubpackCotId(subpackCotDomain.getId());
//                map.put("subpackCotDetailAndSubList", subpackCotIdList);
//                //带出清单模式
//                List<SubpackCotListDomain> subpackCotLists = subpackCotListService.selectBySubpackCotId(subpackCotDomain.getId());
//                map.put("subpackCotLists", subpackCotLists);
//                //带出月度比例
//                List<SubpackCotRate> subpackCotRateList = subpackCotRateService.selectBySubpackCotId(subpackCotDomain.getId());
//                map.put("subpackCotRateList", subpackCotRateList);
//                //带出附件
//                List<SubpackCotAtt> subpackCotAttList = subpackCotAttService.selectBySubpackCotId(subpackCotDomain.getId());
//                map.put("subpackCotAttList", subpackCotAttList);
//            }
//        }
//        catch (Exception e) {
//            log.error("查询分包合同记录异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }

    /**
     * 返回子项名和费用类型数组(子项1##费用名称1)
     * @param request
     * @return
     * @throws Exception
     */
//    @RequestMapping("/getSubAndTypeName")
//    @ResponseBody
//    public Map<String, Object> getSubAndTypeName(HttpServletRequest request) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        String proCodeAndCodes = request.getParameter("proCodeAndCodes");
//        String[] split = proCodeAndCodes.split("\\_");
//        try {
//            //带出内部协议的信息
//            List<InnerAgrt> versionNoByProCode = innerAgrtService.selectVersionNoByProCode(
//                split[0], "9", null);
//            if (versionNoByProCode.size() > 0) {
//                //带出 合同清单子项  和  合同清单子项费用明细  信息
//                List<InnerAgrtDetailAndSubDomain> innerAgrtIdList = innerAgrtDetailService.selectByInnerAgrtId(versionNoByProCode.get(
//                    0).getId());
//                StringBuilder stringBuilder = new StringBuilder();
//                for (InnerAgrtDetailAndSubDomain iSubDomain : innerAgrtIdList) {
//                    stringBuilder.append(iSubDomain.getSubName() + "##" + iSubDomain.getTypeName()
//                                         + ",");
//                }
//                stringBuilder.deleteCharAt(stringBuilder.length() - 1).toString();
//                map.put("stringBuilder", stringBuilder);
//            }
//        }
//        catch (Exception e) {
//            log.error("查询子项记录异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }

//    /**
//     * 分包合同-新增
//     */
//    @SuppressWarnings("rawtypes")
//    @RequestMapping("/save")
//    @ResponseBody
//    public RspVo save(SubpackCotAssist subpackCotAssist) {
//
//        //主表-分包合同
//        subpackCotAssist.setHrDeptId(subpackCotAssist.getHrDeptid());
//        subpackCotAssist.setHrOrgId(subpackCotAssist.getHrOrgid());
//        subpackCotAssist.setStaffName(subpackCotAssist.getStaffname());
//        subpackCotAssist.setHrStaffApplyId(subpackCotAssist.getHrStaffApplyid());
//        String proCode = "";
//        String code = "";
//        String[] strCodes = subpackCotAssist.getProCodeAndCodes().split("\\_");
//        proCode = strCodes[0];
//        code = strCodes[1];
//        subpackCotAssist.setProCode(proCode);
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//        String id = IdFactory.getUUIDUpper();
//        //添加项目名称
//        subpackCotAssist.setProName(strCodes[2]);
//        //父关联id  第一次添加时为  原合同
//        subpackCotAssist.setRefId(code);
//        subpackCotAssist.setId(id);
//        subpackCotAssist.setAddBy(vo.getId());
//        subpackCotAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//        String codes = codeGeneratorConfigService.generatorCode("bpa_subpack_cot");
//        subpackCotAssist.setCodes(codes);
//        //合同类型  先设置成  原合同  如果是补充协议的话  就会在 下面if中 形成覆盖
//        subpackCotAssist.setExtType("1");
//        //合同版本 先设置成   原合同  每次提交时都进行 累加
//        subpackCotAssist.setVersionNo(1);
//        // 处理processId
//        subpackCotAssist.setProcessId(IdFactory.getUUIDUpper());
//        subpackCotAssist.setProcessStatus("1");//审批中
//        subpackCotAssist.setTypes("1");//PPP项目
//        subpackCotAssist.setUptBy(vo.getId());
//        subpackCotAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//
//        //分包合同对应月度付款比例
//        List<SubpackCotRate> subpackCotRates = new ArrayList<SubpackCotRate>();
//        //序号
//        String[] showIdxRates = subpackCotAssist.getShowIdxRates();
//        if (showIdxRates != null && showIdxRates.length > 0) {
//            for (int i = 0; i < showIdxRates.length; i++ ) {
//                String showIdxRate = showIdxRates[i];
//                String minValue = subpackCotAssist.getMinValues()[i];
//                String maxValue = subpackCotAssist.getMaxValues()[i];
//                String payRate = subpackCotAssist.getPayRates()[i];
//                if (StringUtils.isEmpty(showIdxRate)) {
//                    continue;
//                }
//                SubpackCotRate subpackCotRate = new SubpackCotRate();
//                String innerAgrtRateId = IdFactory.getUUIDUpper();//自动生成主键
//                subpackCotRate.setId(innerAgrtRateId);
//                subpackCotRate.setSubpackCotId(id);
//                subpackCotRate.setShowIdx(Integer.parseInt(showIdxRate));
//                subpackCotRate.setMaxValue(new BigDecimal(maxValue));
//                subpackCotRate.setMinValue(new BigDecimal(minValue));
//                subpackCotRate.setPayRate(new BigDecimal(payRate));
//                subpackCotRate.setAddBy(vo.getId());
//                subpackCotRate.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                subpackCotRates.add(subpackCotRate);
//            }
//        }
//
//        //新增分包合同清单分解子项信息
//        List<SubpackCotSub> subpackCotSubs = new ArrayList<SubpackCotSub>();
//        //分包合同清单分解子项费用明细
//        List<SubpackCotDetail> subpackCotDetails = new ArrayList<SubpackCotDetail>();
//        //清单模式
//        List<SubpackCotList> subpackCotLists = new ArrayList<SubpackCotList>();
//        if ("2".equals(subpackCotAssist.getJudge())) {
//            //判断补充协议名称是否存在
//            List<SubpackCot> subpackCot = subpackCotService.isExistSubpackCotSaName(
//                subpackCotAssist.getSubpackCotSaName(), proCode);
//            if (CollectionUtils.isNotEmpty(subpackCot)) {
//                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("补充协议名称【"
//                                                                + subpackCotAssist.getSubpackCotSaName()
//                                                                + "】已经存在~");
//            }
//            //合同类型  覆盖上面的合同类型
//            subpackCotAssist.setExtType("2");
//            //合同版本  每次提交时都进行 累加
//            SubpackCot subpackCot3 = new SubpackCot();
//            subpackCot3.setRefId(code);
//            List<SubpackCot> entityWhere = subpackCotService.selectByEntityWhere(subpackCot3);
//            Integer versionNo = entityWhere.size() + 2;
//            subpackCotAssist.setVersionNo(versionNo);
//            //父关联id  添加时为  补充协议合同  原合同id
//            subpackCotAssist.setRefId(code);
//            subpackCotAssist.setSubpackCotName(strCodes[3]);
//        }
//        else {
//            //判断分包合同名称是否存在
//            List<SubpackCot> subpackCot = subpackCotService.isExistSubpackCotName(
//                subpackCotAssist.getSubpackCotName(), proCode);
//            if (CollectionUtils.isNotEmpty(subpackCot)) {
//                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("分包合同名称【"
//                                                                + subpackCotAssist.getSubpackCotName()
//                                                                + "】已经存在~");
//            }
//        }
//
//        if ("1".equals(subpackCotAssist.getCotType())) {
//            //子项名称
//            String[] subNames = subpackCotAssist.getSubNames();
//            if (subNames != null && subNames.length > 0) {
//                for (int i = 0; i < subNames.length; i++ ) {
//                    String subName = subNames[i];
//                    if (StringUtils.isEmpty(subName) && StringUtils.isEmpty(subName)) {
//                        continue;
//                    }
//                    SubpackCotSub subpackCotSub = new SubpackCotSub();
//                    String subpackCotSubId = IdFactory.getUUIDUpper();//自动生成主键
//                    subpackCotSub.setId(subpackCotSubId);
//                    subpackCotSub.setSubpackCotId(id);
//                    subpackCotSub.setSubName(subName);
//                    subpackCotSub.setAddBy(vo.getId());
//                    Date addTime = top.infopub.mgr.util.DateUtils.addSeconds(
//                        top.infopub.mgr.util.DateUtils.getCurrentDateTime(), i);
//                    subpackCotSub.setAddTime(addTime);
//                    subpackCotSubs.add(subpackCotSub);
//                }
//
//                //费用大类
//                String[] feeTypes = subpackCotAssist.getFeeTypes();
//                for (int j = 0; j < feeTypes.length; j++ ) {
//                    String feeType = feeTypes[j];
//                    String feeSmallType = subpackCotAssist.getFeeSmallTypes()[j];
//                    String itemNameSub = subpackCotAssist.getItemNameSub()[j];
//                    String typeName = subpackCotAssist.getTypeNames()[j];
//                    String orderIdx = subpackCotAssist.getOrderIdxs()[j];
//                    String innerDownRate = subpackCotAssist.getInnerDownRates()[j];
//                    String outDownRate = subpackCotAssist.getOutDownRates()[j];
//                    String afterDownFee = subpackCotAssist.getAfterDownFees()[j];
//                    String preTotal = subpackCotAssist.getPreTotals()[j];
//                    String subpackPre = subpackCotAssist.getSubpackPres()[j];
//                    if (StringUtils.isEmpty(feeType)) {
//                        continue;
//                    }
//                    SubpackCotDetail subpackCotDetail = new SubpackCotDetail();
//                    String subpackCotDetailId = IdFactory.getUUIDUpper();//自动生成主键
//                    subpackCotDetail.setId(subpackCotDetailId);
//
//                    subpackCotDetail.setCotSubId(itemNameSub);
//
//                    subpackCotDetail.setSubpackCotId(id);
//                    subpackCotDetail.setFeeType(1);
//                    subpackCotDetail.setOrderIdx(orderIdx);
//                    subpackCotDetail.setTypeName(typeName);
//                    if ("-1".equals(feeSmallType)) {
//                        subpackCotDetail.setFeeSmallType(Integer.parseInt(feeSmallType));
//                    }
//                    else {
//                        String feeSmallType1 = feeSmallType.charAt(0) + ""
//                                               + feeSmallType.charAt(2);
//                        subpackCotDetail.setFeeSmallType(Integer.parseInt(feeSmallType1));
//                    }
//                    subpackCotDetail.setPreTotal(new BigDecimal(preTotal));
//                    subpackCotDetail.setSubpackPre(new BigDecimal(subpackPre));
//                    subpackCotDetail.setOutDownRate(new BigDecimal(outDownRate));
//                    subpackCotDetail.setAfterDownFee(new BigDecimal(afterDownFee));
//                    subpackCotDetail.setInnerDownRate(new BigDecimal(innerDownRate));
//                    subpackCotDetail.setAddBy(vo.getId());
//                    subpackCotDetail.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                    subpackCotDetails.add(subpackCotDetail);
//                }
//
//                for (SubpackCotDetail subpackCotDetail : subpackCotDetails) {
//                    for (SubpackCotSub subpackCotSub : subpackCotSubs) {
//                        if (subpackCotDetail.getCotSubId().equals(subpackCotSub.getSubName())) {
//                            subpackCotDetail.setCotSubId(subpackCotSub.getId());
//                            break;
//                        }
//                    }
//                }
//
//            }
//        }
//        else if ("2".equals(subpackCotAssist.getCotType())) {
//            String[] showIdxLists = subpackCotAssist.getShowIdxLists();
//            if (showIdxLists != null && showIdxLists.length > 0) {
//                for (int j = 0; j < showIdxLists.length; j++ ) {
//                    String showIdxList = showIdxLists[j];
//                    String subNameList = subpackCotAssist.getSubNameLists()[j];
//                    String subUnitList = subpackCotAssist.getSubUnitLists()[j];
//                    String cotNumList = subpackCotAssist.getCotNumLists()[j];
//                    String cotUnitPriceList = subpackCotAssist.getCotUnitPriceLists()[j];
//                    String cotSumPriceList = subpackCotAssist.getCotSumPriceLists()[j];
//                    SubpackCotList subpackCotList = new SubpackCotList();
//                    String subpackCotListId = IdFactory.getUUIDUpper();//自动生成主键
//                    subpackCotList.setId(subpackCotListId);
//                    subpackCotList.setSubpackCotId(id);
//                    subpackCotList.setShowIdx(Integer.parseInt(showIdxList));
//                    subpackCotList.setSubName(subNameList);
//                    subpackCotList.setSubUnit(subUnitList);
//                    subpackCotList.setCotNums(new BigDecimal(cotNumList));
//                    subpackCotList.setCotUnitPrice(new BigDecimal(cotUnitPriceList));
//                    subpackCotList.setCotSumPrice(new BigDecimal(cotSumPriceList));
//                    subpackCotList.setAddBy(vo.getId());
//                    subpackCotList.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
//                    subpackCotLists.add(subpackCotList);
//                }
//            }
//        }
//
//        //上传附件
//        //1=Word版合同文本
//        List<SubpackCotAtt> subpackCotAtts = new ArrayList<SubpackCotAtt>();
//        String[] fileAtt1 = subpackCotAssist.getFileAtts1();
//        if (fileAtt1 != null) {
//            for (String file : fileAtt1) {
//                SubpackCotAtt subpackCotAtt = createFileAtt(vo, id, file,
//                    subpackCotAssist.getExtType());
//                subpackCotAtt.setTypes("1");
//                subpackCotAtts.add(subpackCotAtt);
//            }
//        }
//        //2=PDF版合同文本
//        String[] fileAtt2 = subpackCotAssist.getFileAtts2();
//        if (fileAtt2 != null) {
//            for (String file : fileAtt2) {
//                SubpackCotAtt subpackCotAtt = createFileAtt(vo, id, file,
//                    subpackCotAssist.getExtType());
//                subpackCotAtt.setTypes("2");
//                subpackCotAtts.add(subpackCotAtt);
//            }
//        }
//        //3=盖章版合同文本（选填）
//        String[] fileAtt3 = subpackCotAssist.getFileAtts3();
//        if (fileAtt3 != null) {
//            for (String file : fileAtt3) {
//                SubpackCotAtt subpackCotAtt = createFileAtt(vo, id, file,
//                    subpackCotAssist.getExtType());
//                subpackCotAtt.setTypes("3");
//                subpackCotAtts.add(subpackCotAtt);
//            }
//        }
//        //4=其他（选填）
//        String[] fileAtt4 = subpackCotAssist.getFileAtts4();
//        if (fileAtt4 != null) {
//            for (String file : fileAtt4) {
//                SubpackCotAtt subpackCotAtt = createFileAtt(vo, id, file,
//                    subpackCotAssist.getExtType());
//                subpackCotAtt.setTypes("4");
//                subpackCotAtts.add(subpackCotAtt);
//            }
//        }
//        subpackCotService.saveSubpackCot(subpackCotAssist, subpackCotSubs, subpackCotDetails,
//            subpackCotLists, subpackCotRates, subpackCotAtts);
//        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "商务管理 -对内合同-分包合同：项目名="
//                                                              + subpackCotAssist.getProName(),
//            null);
//        return RspVo.getSuccessResponse();
//    }
//
//    /**
//     * 分包合同-补充签订
//     * @throws ParseException
//     */
//    @SuppressWarnings("rawtypes")
//    @RequestMapping("/sign")
//    @ResponseBody
//    public RspVo sign(HttpServletRequest request, SubpackCotVo subpackCotVo)
//        throws ParseException {
//        String[] fileAtt1 = request.getParameterValues("fileAtt1");
//        String[] fileAtt2 = request.getParameterValues("fileAtt2");
//        String[] fileAtt3 = request.getParameterValues("fileAtt3");
//        String[] fileAtt4 = request.getParameterValues("fileAtt4");
//
//        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
//        String id = subpackCotVo.getId();
//        List<SubpackCotAtt> subpackCotAtts = new ArrayList<SubpackCotAtt>();
//        if (fileAtt1 != null) {
//            for (String file : fileAtt1) {
//                SubpackCotAtt subpackCotAtt = createFileAtt(vo, id, file, "1");
//                subpackCotAtt.setTypes("1");
//                subpackCotAtts.add(subpackCotAtt);
//            }
//        }
//        if (fileAtt2 != null) {
//            for (String file : fileAtt2) {
//                SubpackCotAtt subpackCotAtt = createFileAtt(vo, id, file, "1");
//                subpackCotAtt.setTypes("2");
//                subpackCotAtts.add(subpackCotAtt);
//            }
//        }
//        if (fileAtt3 != null) {
//            for (String file : fileAtt3) {
//                SubpackCotAtt subpackCotAtt = createFileAtt(vo, id, file, "1");
//                subpackCotAtt.setTypes("3");
//                subpackCotAtts.add(subpackCotAtt);
//            }
//        }
//        if (fileAtt4 != null) {
//            for (String file : fileAtt4) {
//                SubpackCotAtt subpackCotAtt = createFileAtt(vo, id, file, "1");
//                subpackCotAtt.setTypes("4");
//                subpackCotAtts.add(subpackCotAtt);
//            }
//        }
//        subpackCotService.sign(subpackCotVo, subpackCotAtts);
//        LogUtil.bizLog(LogUtil.LogModelType.PROJECT, LogUtil.AcctionType.ADD,
//            "商务管理 -对内合同-补充签订分包合同：项目名=" + subpackCotVo.getProName(), null);
//        return RspVo.getSuccessResponse();
//    }
//
//    private SubpackCotAtt createFileAtt(AuthorizationVO vo, String subpackCotId, String file,
//                                        String extType) {
//        //资料信息数组
//        String[] fileAttStr = file.split("\\|");
//        SubpackCotAtt fileAtt = new SubpackCotAtt();
//        if (extType.equals("1")&& StringUtils.isNotEmpty(fileAttStr[2])) {
//            fileAtt.setId(fileAttStr[2]);
//        }
//        else {
//            fileAtt.setId(IdFactory.getUUIDUpper());
//        }
//        fileAtt.setSubpackCotId(subpackCotId);//项目id
//        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
//        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
//            fileAttStr[1].length()).toLowerCase();//后缀转小写
//        fileAtt.setFileName(fileName);//文件名
//        fileAtt.setFileSuffix(suffix);//文件后缀
//        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
//        fileAtt.setAddBy(vo.getId());//添加人
//        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
//        return fileAtt;
//    }

    /**
     * 上传附件
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    @ResponseBody
    public RspVo updateAtt(HttpServletRequest request) {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> fileMap = multipartHttpServletRequest.getFileMap();
        if (fileMap != null) {
            for (String name : fileMap.keySet()) {
                MultipartFile file = fileMap.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                //上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                //服务器资源路径
                String serverPath = "subpackCot";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add("|" + file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传对内合同-分包合同附件-文件名:"
                                                                      + filePath + "，文件路径:"
                                                                      + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }


//    /**
//     * 分包合同原合同/补充合同-复制单据
//     * @return
//     */
//    @RequestMapping("/toCopy")
//    public String toCopy(HttpServletRequest request) {
//        String id = request.getParameter("id");
//        String extType = request.getParameter("extType");
//        SubpackCotVo subpackCotVo = subpackCotService.queryById(id);
//        request.setAttribute("subpackCot",subpackCotVo);
//        //返回所有合作单位为分包单位的信息
//        List<CoopInfo> coopInfoList = coopInfoService.selectAll(null, "4", null);
//        request.setAttribute("coopInfoList", coopInfoList);
//        if ("1".equals(extType)) {
//            return "bpa/lay-subpackCot-copy-1";
//        }
//        else if ("2".equals(extType)) {
//            return "bpa/lay-subpackCot-copy-2";
//        }
//        return null;
//    }
//    /**
//     * 根据内部协议id查询相关带入信息
//     * @param request
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping("/getSubpackCotById")
//    @ResponseBody
//    public Map<String, Object> getSubpackCotById(HttpServletRequest request) {
//        boolean flag = true;
//        Map<String, Object> map = new HashMap<String, Object>();
//        String proCodeAndCodes = request.getParameter("proCodeAndCodes");
//        String[] strCodes = proCodeAndCodes.split("\\_");
//        try {
//            SubpackCotVo subpackCotVo = subpackCotService.queryById(strCodes[1]);
//            map.put("subpackCotVo", subpackCotVo);
//        }catch(Exception e) {
//            log.error("查询分包合同记录异常", e);
//            flag = false;
//        }
//        map.put("flag", flag);
//        return map;
//    }
}
